package com.liu.es.test;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

public class ESTest_Doc_Insert_Batch {
    public static void main(String[] args) throws Exception {

        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );

        //批量插入数据
        //创建批量对象
        BulkRequest request = new BulkRequest();

        //往批量操作对象添加数据
        //对数据的增加操作就是IndexRequest，而删除操作则是DeleteRequest，其中IndexRequest在绑定ES里的文档后可以用source方法指定要添加的内容，source方法每两个参数作为一个模块
        request.add(new IndexRequest().index("user").id("1001").source(XContentType.JSON, "name", "zhangsan", "age", 24, "sex", "男"));
        request.add(new IndexRequest().index("user").id("1002").source(XContentType.JSON, "name", "lisi", "age", 35, "sex", "女"));
        request.add(new IndexRequest().index("user").id("1003").source(XContentType.JSON, "name", "wangwu", "age", 32, "sex", "女"));
        request.add(new IndexRequest().index("user").id("1004").source(XContentType.JSON, "name", "zhaoliu", "age", 70, "sex", "男"));
        request.add(new IndexRequest().index("user").id("1005").source(XContentType.JSON, "name", "xiongda", "age", 10, "sex", "女"));
        request.add(new IndexRequest().index("user").id("1006").source(XContentType.JSON, "name", "xionger", "age", 35, "sex", "男"));


        BulkResponse responses = esClient.bulk(request, RequestOptions.DEFAULT);

        System.out.println(responses.getItems());
        System.out.println(responses.getIngestTookInMillis());

        esClient.close();
    }
}
